#include "Packet.h"
#include <cstring>

CSimplePacket::CSimplePacket(size_t initial_size) {
    if (initial_size > 0) {
        data.resize(initial_size);
    }
}

CSimplePacket::CSimplePacket(const char* data, size_t size) {
    SetData(data, size);
}

void CSimplePacket::SetData(const char* input_data, size_t size) {
    if (input_data && size > 0) {
        data.assign(input_data, input_data + size);
    } else {
        data.clear();
    }
}

void CSimplePacket::Append(const char* input_data, size_t size) {
    if (input_data && size > 0) {
        data.insert(data.end(), input_data, input_data + size);
    }
}

void CSimplePacket::Resize(size_t new_size) {
    data.resize(new_size);
}

std::unique_ptr<CCPacketBase> CSimplePacket::Clone() const {
    return std::unique_ptr<CCPacketBase>(new CSimplePacket(GetData(), GetSize()));
}

int CWspack::Pack(const char* data, size_t size) {
    if (!data || size == 0) return ERR_SUCCESS;
    
    buffer.clear();
    // Simple packing: add size prefix
    uint32_t packet_size = static_cast<uint32_t>(size);
    buffer.insert(buffer.end(), reinterpret_cast<const char*>(&packet_size), 
                   reinterpret_cast<const char*>(&packet_size) + sizeof(packet_size));
    buffer.insert(buffer.end(), data, data + size);
    
    return ERR_SUCCESS;
}

int CWspack::Unpack(const char* data, size_t size) {
    if (!data || size < sizeof(uint32_t)) return ERR_SOCKET;
    
    // Extract size prefix
    uint32_t packet_size;
    memcpy(&packet_size, data, sizeof(packet_size));
    
    if (size < sizeof(uint32_t) + packet_size) {
        return ERR_SOCKET; // Incomplete packet
    }
    
    buffer.clear();
    buffer.insert(buffer.end(), data + sizeof(uint32_t), data + sizeof(uint32_t) + packet_size);
    
    return ERR_SUCCESS;
}